package com.jt.service;

import com.jt.vo.ImageVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;

@PropertySource("classpath:properties/img.properties")
@Service
public class FileServiceImpl implements FileService {
    private static Set<String> sets = new HashSet<>();

    static {
        sets.add(".jpg");
        sets.add(".png");
        sets.add(".img");
    }

    @Value("${image.localPath}")
    private String localPath;
    @Value("${image.urlName}")
    private String urlName;


    @Override
    public ImageVO upload(MultipartFile upLoadFile) {


        String fileName = upLoadFile.getOriginalFilename();
        String temFileName = fileName.toLowerCase();
        temFileName = temFileName.substring(temFileName.lastIndexOf("."));
        if (!sets.contains(temFileName)) {
            return ImageVO.fail();
        }

        try {
            BufferedImage bufferedImage = ImageIO.read(upLoadFile.getInputStream());
            int height = bufferedImage.getHeight();
            int width = bufferedImage.getWidth();

            String time = new SimpleDateFormat("/yyyy/MM/dd/").format(new Date());
            localPath += time;
            File file = new File(localPath);
            if (!file.exists()) file.mkdirs();
            String uuid = UUID.randomUUID().toString();

            fileName = localPath + uuid;
            upLoadFile.transferTo(new File(fileName));

            return ImageVO.success(width, height, urlName + time + fileName);
        } catch (IOException e) {
            e.printStackTrace();
            return ImageVO.fail();
        }


    }
}